const router = require("koa-router")();
const main = require("../models");

router.get("/login", async ctx => {
    var arr = ["html", "css", "js"]
    await ctx.render("login", { arr })
})
router.get("/register", async ctx => {
    await ctx.render("register")
})
router.get("/home", async ctx => {
    ctx.body = "首页"
})

router.post("/doRegister", async ctx => {
    var { username, pwd } = ctx.request.body;
    var userCollection = await main("user");
    /**对user表查询 没有usename才添加 */
    var res = await userCollection.find({ username }).toArray();
    if (res.length) {
        ctx.body = "<script>alert('用户名已存在');location.href='/register'</script>"
    } else {
        var res = await userCollection.insertOne({ username, pwd })
        ctx.body = "<script>alert('注册成功');location.href='/home'</script>"
    }
})

router.post("/doLogin", async ctx => {
    var { username, pwd } = ctx.request.body;
    var userCollection = await main("user");
    var res = await userCollection.find({username,pwd}).toArray();
    if(res.length){
        // ctx.body = "<script>location.href='/home'</script>"
        await ctx.redirect("/home")
    }else{
        ctx.body = "<script>alert('用户名或密码错误');location.href='/login'</script>"
    }
})

module.exports = router;